package com.example.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.R;
import com.example.common.entity.SiftParams;
import com.example.common.utils.Util;
import com.example.sys.entity.Menus;
import com.example.sys.mapper.MenuMapper;
import com.example.sys.service.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author 罗文斌
 * @Date 2023/7/20
 * @Version 1.0.0
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menus> implements MenuService {

    @Override
    public R getMenus(String params) {
        SiftParams siftParams = Util.transformParams(params, SiftParams.class);
        Page<Menus> page = new Page<>(siftParams.getCurrent(), siftParams.getSize());
        QueryWrapper<Menus> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(siftParams.getSiftName()), "label", siftParams.getSiftName());
        wrapper.orderByAsc("parent").orderByAsc("sort");
        Page<Menus> menusPage = baseMapper.selectPage(page, wrapper);
        JSONObject rs = new JSONObject();
        rs.put("total", menusPage.getTotal());
        rs.put("data", menusPage.getRecords());
        return R.success(rs);
    }

    @Override
    public R getAllMenus() {
        QueryWrapper<Menus> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("parent").orderByAsc("sort");
        List<Menus> menus = baseMapper.selectList(wrapper);
        return R.success(menus);
    }

    @Override
    public R addMenus(String params) {
        Menus menus = Util.transformParams(params, Menus.class);
        int rs = baseMapper.insert(menus);
        return rs > 0 ? R.success("添加成功") : R.error("添加失败");
    }

    @Override
    public R updateMenus(String params) {
        Menus menus = Util.transformParams(params, Menus.class);
        int rs = baseMapper.updateById(menus);
        return rs > 0 ? R.success("修改成功") : R.error("修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeMenu(String params) {
        try {
            Menus menus = Util.transformParams(params, Menus.class);
            baseMapper.deleteById(menus.getId());
            baseMapper.removeRoleMenu(menus.getId());
            if(menus.getParent() == 0) {
                baseMapper.changeParent(menus.getId());
            }
        } catch (Exception e) {
            log.error("执行错误：", e);
            R.error("删除失败");
        }
        return R.success("删除成功");
    }
}
